package com.aiyun.securiy.login.security.custom;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

	private final UserDetailsService userDetailsService;

	private final PasswordEncoder passwordEncoder;


	public CustomAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
		this.userDetailsService = userDetailsService;
		this.passwordEncoder = passwordEncoder;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String username = authentication.getPrincipal().toString();
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		boolean matches = passwordEncoder.matches(authentication.getCredentials().toString(), userDetails.getPassword());
		if (matches) {
			return new UsernamePasswordAuthenticationToken(
					authentication.getPrincipal(),
					authentication.getCredentials(),
					userDetails.getAuthorities()
			);
		}else {
			throw new BadCredentialsException("用户名或密码错误");
		}
	}

	@Override
	public boolean supports(Class<?> aClass) {
		return true;
	}
}
